package com.code2roc.fastboot.framework.security;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.Ssl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class TomcatConfig {
    @Autowired
    private SecurityConfig securityConfig;
    @Value("${server.port}")
    private int serverPort;

    @Bean
    @ConditionalOnProperty(name = "system.package", havingValue = "jar", matchIfMissing = true)
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcatServletContainerFactory = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                SecurityCollection collection = new SecurityCollection();
                //http方法
                List<String> forbiddenList = Arrays.asList("PUT|DELETE|HEAD|TRACE".split("\\|"));
                for (String method : forbiddenList) {
                    collection.addMethod(method);
                }
                //url匹配表达式
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcatServletContainerFactory.addConnectorCustomizers(new FrameTomcatConnectorCustomizer());
        return tomcatServletContainerFactory;
    }

    class FrameTomcatConnectorCustomizer implements TomcatConnectorCustomizer {
        @Override
        public void customize(Connector connector) {
            Http11NioProtocol protocal=(Http11NioProtocol)connector.getProtocolHandler();
            protocal.setMaxConnections(20000);//最大连接数
            protocal.setMaxThreads(500);//最大线程数
            protocal.setMaxHttpHeaderSize(20480000);//请求头大小
        }
    }
}
